package code.command {

import code.Model;
import code.event.SearchEvent;
import code.vo.Category;
import code.vo.Topic;

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;
import com.adobe.utils.StringUtil;

import logging.Logger;

import mx.collections.IHierarchicalCollectionView;

public class SearchCommand implements ICommand {
	
	private static const LOG: Logger = Logger.getLogger("code.command.SearchCommand");
	
	
	public function SearchCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: SearchEvent = _event as SearchEvent;
		LOG.fine("Executing search [event="+event+"].");
		
		const oData: IHierarchicalCollectionView = IHierarchicalCollectionView(Model.instance.offeredTopicsAdvancedDataGridHack.dataProvider);
		const nData: IHierarchicalCollectionView = IHierarchicalCollectionView(Model.instance.neededTopicsAdvancedDataGridHack.dataProvider);
		
		var currentSearchRegexp: RegExp;
		var fnFilterTopics: Function;
		if(StringUtil.trim(event.searchTerm) == "") {
			
			if(oData.filterFunction == null) {
				LOG.finer("Aborting search, because reset would not change any data.");
				return;
			}
			
			currentSearchRegexp = null;
			fnFilterTopics = null;
		} else {
			currentSearchRegexp = new RegExp(event.searchTerm, "i");
			fnFilterTopics = function filterSome(item: Object): Boolean {
				if(item is Category) {
					return true;
				}
				const topic: Topic = item as Topic;
				return topic.title.match(currentSearchRegexp) != null;
			};
		}
		
		oData.filterFunction = fnFilterTopics;
		oData.refresh();
		
		nData.filterFunction = fnFilterTopics;
		nData.refresh();
		
		/*
		this.eachCategories(function(category: Category): void {
			category.topics.filterFunction = fnFilterTopics;
			category.topics.refresh();
		});
		Model.instance.offeredTopicsAdvancedDataGridHack.invalidateList();
		Model.instance.neededTopicsAdvancedDataGridHack.invalidateList();
		*/
	}
	
	/*
	private function eachCategories(fnBlock: Function): void {
		for each(var ocat: Category in Model.instance.offeredCategories) {
			fnBlock(ocat);
		}
		for each(var ncat: Category in Model.instance.neededCategories) {
			fnBlock(ncat);
		}
	}
	*/
}
}